/**
 * Created by Administrator on 13-12-31.
 */
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"net/rpc"
	"os"
	"strconv"
	"time"
	"runtime"
	// "reflect"
)

const (
	DeviceNum = 100
	PointNum  = 100
)
var Data string 

type Args struct {
	// I, J int
	I int
}
var multResult []byte
type MyMethod int

type Grid struct {
	Lists []PointGroup `json:product`
}

type PointGroup struct {
	Ciid  string
	Value string
	Aste  int
	Time string
}


func (this *MyMethod) DataSource(args *Args, reply *[]byte) error {
    if args == nil || reply == nil {
		return errors.New("nil paramters !")
	}
    var stb Grid
    json.Unmarshal([]byte(multResult), &stb)
    fmt.Printf("json:m,%s\n", len(stb.Lists))
    if args.I>len(stb.Lists){
    	*reply = multResult
    	return nil
    }
    // fmt.Printf("json:m,%s\n",  stb[0])
    var m Grid
    i := 1
    for _, ele := range stb.Lists {
    	m.Lists = append(m.Lists, ele)
    	if i >=args.I{
    	  bytes, _ := json.Marshal(m)
          *reply = bytes
    	  return nil         
    	}
    	i = i + 1
    }
	return nil
}


func (this *MyMethod) Datas( reply *[]byte)error{
	i := 1
	j := 1
	var m Grid
	for i <= DeviceNum {
		for j <= PointNum {
			orderi := PointGroup{Ciid: strconv.Itoa(i) + "." + strconv.Itoa(j), Value: "song", Aste: 0,Time:time.Now().Format("2006-01-02 15:04:05") }
			m.Lists = append(m.Lists, orderi)
			j = j + 1
		}
		i = i + 1
		j = 1
	}
	 bytes, _ := json.Marshal(m)
	// fmt.Printf("json:m,%s\n", bytes)
    *reply = bytes
	 return nil
}


func (this *MyMethod) start(){
	t := time.Tick(1 * time.Second)  
    i := 0  
    
    for now := range t {  
    	this.Datas( &multResult)
    	fmt.Println(now)
        i++  

    }  
}


func main() {
	println("start server at" + "7777")
	mm := new(MyMethod)
	runtime.GOMAXPROCS(1) //设置cpu的核的数量，从而实现高并发
	go mm.start()
	server := rpc.NewServer()
	server.Register(mm)
	listener, err := net.Listen("tcp", ":7777")
	defer listener.Close()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error %s\n", err.Error())
		return
	}
	server.Accept(listener)

}
